
var app = getApp();
var tsc = require("../../utils/tsc.js");
var encode = require("../../utils/encoding.js");

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    checdedTotal: 0,
    printingNum: 0,

    looptime: 0,
    currentTime: 1,
    lastData: 0,
    oneTimeData: 0,
    buffSize: [],
    buffIndex: 0,//发送字节数下标
    printNum: [],
    printNumIndex: 0,
    printerNum: 1,
    currentPrint: 1,
    isLabelSend: false,
    isQuery: false,
    imageSrc: '../../imags/wechat.jpg',
    jpgSrc: '../../imags/flower2.jpg',
    canvasWidth: 100,
    canvasHeight: 100,
    jpgWidth: 200,
    jpgHeight: 200,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    var phone = app.globalData.phone;
    this.getDataList();
  }, 

    //   单击选项
    clickItem: function(e) {
        var index = e.currentTarget.dataset['index'];
        var val = !(this.data.dataList[index].checked);
        this.setData({
            ['dataList[' + index + '].checked']: val
        })
        this.setChecdedTotal();
    },

    //   计算总共已选中数量
    setChecdedTotal: function() {
        let num = 0;
        this.data.dataList.forEach(val => {
            if (val.checked) {
                num++;
            }
        })
        this.setData({
            checdedTotal: num
        })
    },

    // 全选、反选、清空
    setChecdedItem: function(e) {
        var type = e.currentTarget.dataset['clickType'];
        var list = this.data.dataList;
        if (type == 1) {
            list.forEach(val => {
                val.checked = true;
            })
            
        } else if (type == 2) {
            list.forEach(val => {
                val.checked = !val.checked;
            })
        } else if (type == 0) {
            list.forEach(val => {
                val.checked = false;
            })
        }
        this.setData({
            dataList: list
        })
        this.setChecdedTotal();
    },

    // 刷新数据
    refresh: function() {
        this.getDataList();
    },

    // 获取数据
  getDataList: function () {
    var list = [
        {
            id: "16711549517090775056",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明张明张明张明张明张明张明张明张明张明张明张明张明张明张明张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第一份',
            orderTime: '09:02:01',
        },
        {
            id: "167115ty775057",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明张明张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第2份',
            orderTime: '09:02:01',
        },
        {
            id: "16css090777",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第3份',
            orderTime: '09:02:01',
        },
        {
            id: "1671154sdf90775057",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第2份',
            orderTime: '09:02:01',
        },
        {
            id: "16711896777",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第3份',
            orderTime: '09:02:01',
        },
        {
            id: "167458775057",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第2份',
            orderTime: '09:02:01',
        },
        {
            id: "167962090777",
            pickingSerialNo: '135',
            supplyAddress: 'A18',
            nameTakingMeal: '张明',
            nameDishes: '豆蒸排骨( 不辣 +保鸡丁(  ) +小白菜+米饭x1',
            remarks: '第3份',
            orderTime: '09:02:01',
        },
        
    ]

    this.setData({
        // dataList: list
    })
    // return;

    var _this = this;
    var phone = wx.getStorageSync('userPhone')
    wx.showLoading();
    wx.request({
        // 请求的地址如果一http开头直接用url不是http开头添加我们 baseUrL
        url: 'http://btprint.yongshantuan.cn:8000/jeecg-boot/hc/hcOrderMerchant/blueToothPrentData',
        method: 'get',
        data: {
            phone: phone,
        },
        param: {},
        // header,
        success(res){
            if (res.data instanceof Array && res.data.length) {
                _this.setData({dataList: res.data})
            } else {
                wx.showToast({
                    title: '暂无订单',
                    icon: 'none'
                })
            }
            console.log(res);
        },
        fail(err){
          wx.showToast({title:"加载失败，联系管理员",icon:"none"})
             // 请求失败
            //   reject(err);
        },
        complete(){
            _this.setChecdedTotal();
            wx.hideLoading();
        }
    })
    
  },

  // 打印订单按钮
  printData: function() {
    if (this.data.isLabelSend) {
        return;
    }
    var _this = this;

    // 控制打印时间
    var _time = '10:00:00'
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var date2 = year + '/' + month + '/' + day + ' ' + _time;
    var printTime = new Date(date2);
    if (date <= printTime ) {
        wx.showModal({
          title: '提示',
          content: '请在10:00后打印',
          showCancel: false
        })
        return;
    }

    // 检查设备连接状况
    // todo

    // 当前无订单
    if (this.data.dataList.length == 0) {
        wx.showToast({
            title: '当前无订单',
            icon: 'none'
        })
        return;
    }
    // 请选择要打印的订单
    var list = this.data.dataList.filter(val => val.checked == true);
    if (list.length == 0) {
        wx.showToast({
            title: '请选择要打印的订单',
            icon: 'none'
        })
        return
    }
    
    wx.showModal({
      title: '提示',
      content: '确定打印选中的' + list.length + '个订单？',
      complete: (res) => {
        if (res.confirm) {
            _this.setData({printingNum: 0})
            _this.setData({isLabelSend: true})
            print();
        }
      }
    })
    
    
    function print() {
        var i = _this.data.printingNum;
        console.log(i);
        wx.showLoading({
            title: '打印中...' + (i + 1),
        })
        _this.printLabel(list[i]);

        _this.setData({printingNum: i + 1})
        if (_this.data.printingNum < list.length) {
            setTimeout(() => {
                print();
            }, 2000)
        } else {
            setTimeout(() => {
                wx.hideLoading();
                _this.setData({isLabelSend: false})
            }, 1000);
        }
    }

    // this.queryStatus();
 },

// --------------------------------------
  
  initPhoto: function () {//初始化画布数据
    //创建一个png格式
    var that = this
    const ctx_out = wx.createCanvasContext('canvasOut', this);
    var png = that.data.imageSrc;
    wx.getImageInfo({
      src: png,
      success(res) {
        that.setData({
          canvasWidth: res.width,
          canvasHeight: res.height,
        });
        console.log("画布宽度" + res.width, "画布高度" + res.height);
        ctx_out.drawImage(png, 0, 0);
        ctx_out.draw();
      }
    })
    //创建一个jpg格式图片
    const ctx_jpg = wx.createCanvasContext('canvasJPG', this);
    var img = that.data.jpgSrc;
    wx.getImageInfo({
      src: img,
      success(res) {
        that.setData({
          jpgWidth: res.width,
          jpgHeight: res.height,
        });
        console.log("JPG画布宽度" + res.width, "JPG画布高度" + res.height);
        ctx_jpg.drawImage(img, 0, 0, res.width, res.height);
        ctx_jpg.draw();
      }
    })
  },
  

  printLabel: function (item) { //标签测试
    var that = this;
    var command = tsc.jpPrinter.createNew()
    this.setPrintText(command, item);
    command.setPagePrint()//执行打印指令
    that.prepareSend(command.getData())
    console.log(item.id);
  },

  // 设置打印的标签
  setPrintText: function(command, item) {
    command.setCls()//清除缓冲区，防止下一个没生效
    command.setSize(58, 30)//设置标签大小，单位mm.具体参数请用尺子量一下
    command.setGap(0)//设置两个标签之间的间隙，单位mm.具体参数请用尺子量一下
    command.setCls()//清除缓冲区
    // command.setBox(20, 20, 484, 250, 4) //绘制一个边框
    // command.setBar(10, 75, 455, 5);     //绘制一条黑线

    command.setText(35, 40, "TSS24.BF2", 0, 2, 2, "地址:"+ item.supplyAddress)//绘制文字
    command.setText(290, 50, "TSS24.BF2", 0, 1, 1, "序号:" + item.pickingSerialNo)//绘制文字
    command.setText(100, 120, "TSS24.BF2", 0, 2, 2, "姓名:" + item.nameTakingMeal)//绘制文字
    command.setText(50, 180, "TSS24.BF2", 0, 1, 1, "菜品:" + item.nameDishes)//绘制文字
    command.setText(50, 250, "TSS24.BF2", 0, 2, 2, "备注:" + (item.remarks || ''))//绘制文字
  },

  printPhoto: function () {//打印bitmap，图片内容不建议太大，小程序限制传输的字节数为20byte
    var that = this;
    var canvasWidth = that.data.canvasWidth
    var canvasHeight = that.data.canvasHeight
    var command = tsc.jpPrinter.createNew()
    command.setCls()
    command.setSize(30, 30)
    command.setGap(0)
    command.setCls()
    wx.canvasGetImageData({
      canvasId: 'canvasOut',
      x: 0,
      y: 0,
      width: canvasWidth,
      height: canvasHeight,
      success: function (res) {
        console.log("获取画布数据成功")
        command.setBitmap(0, 0, 0, res)
        command.setPrint(1)
        that.prepareSend(command.getData())//发送数据
      },
      complete: function (res) {
        console.log("finish")
      },
      fail: function (res) {
        console.log(res)
        wx.showToast({
          title: '获取画布数据失败',
          icon: 'none',
        })
      }
    })
  },

  prepareSend: function (buff) { //准备发送，根据每次发送字节数来处理分包数量
    // console.log('buff',buff)
    var that = this
    var time = that.data.oneTimeData
    var looptime = parseInt(buff.length / time);
    var lastData = parseInt(buff.length % time);
    //console.log(looptime + "---" + lastData)
    that.setData({
      looptime: looptime + 1,
      lastData: lastData,
      currentTime: 1,
    })
    that.Send(buff)
  },
  queryStatus: function () {//查询打印机状态
    var that = this
    var buf;
    var dateView;
    /*
    n = 1：传送打印机状态
    n = 2：传送脱机状态
    n = 3：传送错误状态
    n = 4：传送纸传感器状态
    */
    buf = new ArrayBuffer(5)
    dateView = new DataView(buf)
    dateView.setUint8(0, 27)
    dateView.setUint8(1, 33)
    dateView.setUint8(2, 63)
    dateView.setUint8(3, 13)
    dateView.setUint8(4, 10)
    wx.writeBLECharacteristicValue({
      deviceId: app.BLEInformation.deviceId,
      serviceId: app.BLEInformation.writeServiceId,
      characteristicId: app.BLEInformation.writeCharaterId,
      value: buf,
      success: function (res) {
        console.log("发送成功")
        that.setData({
          isQuery: true
        })
      },
      fail: function (e) {
        wx.showToast({
          title: '发送失败',
          icon: 'none',
        })
        //console.log(e)
        return;
      },
      complete: function () {

      }
    })

    wx.notifyBLECharacteristicValueChange({
      deviceId: app.BLEInformation.deviceId,
      serviceId: app.BLEInformation.notifyServiceId,
      characteristicId: app.BLEInformation.notifyCharaterId,
      state: true,
      success: function (res) {
        wx.onBLECharacteristicValueChange(function (r) {
          console.log(`characteristic ${r.characteristicId} has changed, now is ${r}`)
          var result = ab2hex(r.value)
          console.log("返回" + result)
          var tip = ''
          if (result == 0) {//正常
            tip = "正常"
          } else if (result == 4) {//缺纸
            tip = "缺纸"
          } else if (result == 5) {//开盖、缺纸
            tip = "开盖、缺纸"
          } else if (result == 41) {
            tip = "开盖"
          }else if (result == 40) {//其他错误
            tip = "其他错误"
          } else {//未处理错误
            tip = "未知错误"
          }
          wx.showModal({
            title: '打印机状态',
            content: tip,
            showCancel: false
          })

        })
      },
      fail: function (e) {
        wx.showModal({
          title: '打印机状态',
          content: '获取失败',
          showCancel: false
        })
        console.log(e)
      },
      complete: function (e) {
        that.setData({
          isQuery: false
        })
        console.log("执行完成")
      }
    })
  },
  Send: function (buff) { //分包发送
    var that = this
    var currentTime = that.data.currentTime
    var loopTime = that.data.looptime
    var lastData = that.data.lastData
    var onTimeData = that.data.oneTimeData
    var printNum = that.data.printerNum
    var currentPrint = that.data.currentPrint
    var buf
    var dataView
    if (currentTime < loopTime) {
      buf = new ArrayBuffer(onTimeData)
      dataView = new DataView(buf)
      for (var i = 0; i < onTimeData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
      }
    } else {
      buf = new ArrayBuffer(lastData)
      dataView = new DataView(buf)
      for (var i = 0; i < lastData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
      }
    }
    //console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
    wx.writeBLECharacteristicValue({
      deviceId: app.BLEInformation.deviceId,
      serviceId: app.BLEInformation.writeServiceId,
      characteristicId: app.BLEInformation.writeCharaterId,
      value: buf,
      success: function (res) {
        if (currentPrint == printNum) {
          /* wx.showToast({
            title: '已打印第' + currentPrint + '张',
          }) */
        }
        console.log('打印第' + (that.data.printingNum + 1) + '张',)
      },
      fail: function (e) {
        console.log(e, '第' + currentPrint + '张失败',)
      },
      complete: function () {
        currentTime++
        if (currentTime <= loopTime) {
          that.setData({
            currentTime: currentTime
          })
          that.Send(buff)
        } else {
          // wx.showToast({
          //   title: '已打印第' + currentPrint + '张',
          // })`
          if (currentPrint == printNum) {
            that.setData({
              looptime: 0,
              lastData: 0,
              currentTime: 1,
            //   isLabelSend: false,
              currentPrint: 1
            })
          } else {
            currentPrint++
            that.setData({
              currentPrint: currentPrint,
              currentTime: 1,
            })
            that.Send(buff)
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initPriter();
  },

    // 初始化打印机  
  initPriter:function() {
    var list = []
    var numList = []
    var j = 0
    for (var i = 20; i < 200; i += 10) {
      list[j] = i;
      j++
    }
    for (var i = 1; i < 10; i++) {
      numList[i - 1] = i
    }
    this.setData({
      buffSize: list,
      oneTimeData: list[0],
      printNum: numList,
      printerNum: numList[0]
    })
    this.initPhoto();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },


  buffBindChange: function (res) { //更改打印字节数
    var index = res.detail.value
    var time = this.data.buffSize[index]
    this.setData({
      buffIndex: index,
      oneTimeData: time
    })
  },
  printNumBindChange: function (res) { //更改打印份数
    var index = res.detail.value
    var num = this.data.printNum[index]
    this.setData({
      printNumIndex: index,
      printerNum: num
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //关闭蓝牙连接
    // wx.closeBLEConnection({
    //   deviceId: app.BLEInformation.deviceId,
    //   success: function(res) {
    //     console.log("关闭蓝牙成功")
    //   },
    // })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})